<?php


namespace app\backstage\controller;


use app\backstage\logic\RechargeLogic;
use app\common\model\QuickLink;
use app\common\model\RechargeActivity;
use app\common\model\RechargeItem;
use app\common\model\RechargeTemplate;
use think\Controller;
use think\Db;

class Recharge extends Controller
{
    protected $middleware = [
        'VerifyJwt' => ['except' => []],
        'VerifyPower' => ['except' => ['refItem']],
    ];

    protected $logic;

    public function __construct(RechargeLogic $logic = null)
    {
        $this->logic = $logic;
        parent::__construct();
    }

    /**
     * 活动列表
     * @return mixed|\think\response\Json
     */
    public function activity()
    {
        if (request()->isAjax()) {
            $where = [];
            $title = input('title');
            if ($title != '') {
                $where[] = ['title', 'like', "%{$title}%"];
            }
            $page = input('page', 1);
            $limit = input('limit', 10);
            return $this->logic->activityList($where, $page, $limit);
        }
        $role = request()->_role;
        $this->assign('alias', $role->alias);
        return $this->fetch();
    }

    /**
     * 设置活动充值
     * @return mixed|\think\response\Json
     */
    public function setActivity()
    {
        if (request()->isAjax()) {
            $params = request()->param();
            $result = $this->validate($params, 'app\backstage\validate\RechargeValidate.setActivity');
            if (true !== $result) {
                $this->error($result);
            }
            if ($params['total_fee'] < 18) {
                $this->error('保存失败，充值金额最低为18元');
            }
            if (!$params['vipdays'] && !$params['virtual_currency']){
                $this->error('会员套餐、充值书币必须选择一样');
            }
            if ($params['vipdays'] && ($params['virtual_currency'] || $params['point_gift'])){
                $this->error('会员套餐、充值书币只能选择一样');
            }
            $id = input('id');
            return $this->logic->setActivity($params, $id);
        }
        $id = input('id');
        $info = RechargeActivity::get($id);
        $this->assign('info', $info);
        return $this->fetch();
    }

    /**
     * 删除活动
     * @return \think\response\Json
     */
    public function delActivity()
    {
        $id = input('id');
        if (!$id) {
            $this->error('参数异常');
        }
        return $this->logic->delActivity($id);
    }

    /**
     * 管理员充值项
     * @return mixed|\think\response\Json
     */
    public function items()
    {
        $user = request()->_user;
        if (request()->isAjax()) {
            $quickId = input('quick_id');
            if ($quickId != '') {
                $where[] = ['quick_id', '=', $quickId];
            } else {
                return sucJson();
            }
            $where[] = ['is_activity', '=', 0];
            $where[] = ['manage_id', '=', 0];
            return $this->logic->itemList($where);
        }

        $qas = \app\common\model\QuickApp::getList();
        $this->assign('qas', $qas);
        $quickId = input('quick_id');
        $this->assign('quick_id', $quickId);
        return $this->fetch();
    }

    /**
     * 管理员设置充值项
     * @Author: whh
     */
    public function setItem()
    {
        $quickId = input('quick_id');
        $user = request()->_user;
        $role = request()->_role;

        if($role->alias == 'agent')
        {
            $myQIds = Db::table('quick_app_mp_manager')->where('uid',$user->id)->column('quick_id');
            if(empty($myQIds))
            {
                return errJson('无权限操作此App');
            }
            if (!in_array($quickId, $myQIds)) {
                return errJson('无权限操作此App');
            }
        }

        $params = request()->param();
        $tableData = $params;
        unset($tableData['quick_id']);
        unset($tableData['_user']);
        unset($tableData['_role']);
        $saveArr = [];
        $keys = ['id', 'total_fee', 'lable_open', 'lable', 'en_lable', 'virtual_currency', 'point_gift', 'vipdays', 'first', 'selected', 'state', 'sort', 'desc', 'en_desc', 'desc2', 'en_desc2'];
        if (!$tableData) {
            $this->error('请添加支付项后再保存');
        }
        foreach ($keys as $key) {
            foreach ($tableData[$key] as $k => $v) {
                $saveArr[$k][$key] = $v;
            }
        }
        foreach ($saveArr as $k => $v) {
            $result = $this->validate($v, 'app\backstage\validate\RechargeValidate.setItem');
            if (true !== $result) {
                $this->error($result);
            }
            $saveArr[$k]['total_fee'] = $v['total_fee'] * 100;
            if (!$saveArr[$k]['virtual_currency'] && !$saveArr[$k]['vipdays']) {
                $this->error('保存失败，必须设置书币或选择套餐');
            }
            if (($saveArr[$k]['virtual_currency'] || $saveArr[$k]['point_gift']) && $saveArr[$k]['vipdays']) {
                $this->error('保存失败，普通充值和会员套餐只能选择一种，请检查支付项');
            }
            if ($v['total_fee'] < 18) {
                $this->error('保存失败，充值金额最低为18元');
            }
        }
        foreach ($saveArr as $k => $v) {
            if (isset($v['id']) && $v['id']) {
                $model = RechargeItem::get($v['id']);
                $model->allowField(true)->save($v);
            } else {
                $model = new RechargeItem;
                $v['quick_id'] = $quickId;
                $v['manage_id'] = 0;
                $model->allowField(true)->save($v);
            }
        }
        $this->success();
    }


    /**
     * 管理员删除充值项
     * @throws \Exception
     * @Author: whh
     */
    public function delItem()
    {
        $id = input('id');
        $item = RechargeItem::get($id);
        if (!$item) {
            $this->success();
        }
        $item->delete();
        $this->success();
    }


    /**
     * 投放号充值项
     * @return mixed|\think\response\Json
     */
    public function channelItems()
    {
        $user = request()->_user;
        $role = request()->_role;

        if ($role->alias != 'channel') {
            return errJson('角色异常');
        }

        if (request()->isAjax()) {

            $items = $this->logic->itemListArray($user->id);

            return sucJson($items);
        }

        return $this->fetch();
    }

    /**
     * 设置投放号充值项
     * @return \think\response\Json
     */
    public function setChannelItem(){

        $role = request()->_role;
        if ($role->alias != 'channel') {
            return errJson('角色异常');
        }
        $user = request()->_user;

        $params = request()->param();
        $tableData = $params;

        unset($tableData['_user']);
        unset($tableData['_role']);

        $saveArr = [];
        $keys = ['id', 'total_fee', 'lable_open', 'lable', 'virtual_currency', 'point_gift', 'vipdays', 'first', 'selected', 'state', 'sort', 'desc'];
        if (!$tableData) {
            $this->error('请添加支付项后再保存');
        }

        $quick_id = Db::table('quick_app_mp_manager')->where('uid',$user->id)->field('quick_id')->findOrEmpty();
        if(empty($quick_id))
        {
            $this->error('该账号未授权App');
        }

        foreach ($keys as $key) {
            foreach ($tableData[$key] as $k => $v) {
                $saveArr[$k][$key] = $v;
                $saveArr[$k]['quick_id'] = $quick_id['quick_id'];
            }
        }

        foreach ($saveArr as $k => $v) {
            $result = $this->validate($v, 'app\backstage\validate\RechargeValidate.setItem');
            if (true !== $result) {
                $this->error($result);
            }
            $saveArr[$k]['total_fee'] = $v['total_fee'] * 100;
            if (!$saveArr[$k]['virtual_currency'] && !$saveArr[$k]['vipdays']) {
                $this->error('保存失败，必须设置书币或选择套餐');
            }
            if (($saveArr[$k]['virtual_currency'] || $saveArr[$k]['point_gift']) && $saveArr[$k]['vipdays']) {
                $this->error('保存失败，普通充值和会员套餐只能选择一种，请检查支付项');
            }
            if ($v['total_fee'] < 18) {
                $this->error('保存失败，充值金额最低为18元');
            }
        }

        foreach ($saveArr as $k => $v) {
            $record = Db::table('pay_recharge_item')->where('id',$v['id'])->field('manage_id')->findOrEmpty();

            if (isset($v['id']) && $v['id']) {

                if($record['manage_id'] != $user->id)
                {
                    unset($v['id']);
                    $v['manage_id'] = $user->id;
                    $model = new RechargeItem;
                    $model->allowField(true)->save($v);
                }else{
                    $v['manage_id'] = $user->id;
                    $model = RechargeItem::get($v['id']);
                    $model->allowField(true)->save($v);
                }

            } else {
                $model = new RechargeItem;
                $v['manage_id'] = $user->id;
                $model->allowField(true)->save($v);
            }
        }

        $this->success();
    }

    /**
     * 投放号删除充值项
     */
    public function delChannelItem(){
        $role = request()->_role;
        if ($role->alias != 'channel') {
            return errJson('角色异常');
        }
        $user = request()->_user;
        $id = input('id');
        $item = RechargeItem::where("id", $id)->where("manage_id", $user->id)->find();
        if (!$item) {
            $this->success();
        }
        $item->delete();
        $this->success();
    }


    /**
     * 同步充值项目
     * @return mixed
     */
    public function syncPayItem(){
        $id = input('id');
        if (request()->isAjax()){
            $fromId = input('fromId');
            if (!$fromId || !$id) {
                $this->error('参数异常');
            }
            if ($fromId == $id) {
                $this->error('同步失败，不能复制本身');
            }
            $temp = new RechargeTemplate();
            $temps = $temp->where("channel_id", $fromId)->select()->toArray();
            if (!$temps) {
                $this->error('同步失败，该账号下充值模版不存在');
            }
            foreach ($temps as $temp){
                $template_id = Db::table("pay_recharge_template")->insertGetId([
                    'channel_id' => $id,
                    'name' => $temp['name'],
                ]);
                $where = [];
                $where[] = ['template_id', '=', $temp['id']];
                $where[] = ['delete_time', '=', 0];
                $items = RechargeItem::where($where)->select()->toArray();
                foreach ($items as $k => $v){
                    unset($v['id']);
                    unset($v['create_time']);
                    unset($v['update_time']);
                    $v['quick_id'] = 0;
                    $v['manage_id'] = $id;
                    $v['template_id'] = $template_id;
                    Db::table("pay_recharge_item")->insert($v);
                }
            }
            $this->success();
        }
        $list = sonUsers('channel');
        $this->assign('list', $list);
        $this->assign('id', $id);
        return $this->fetch();
    }

    /*
     * 投放号充值项
     * */
    public function items_channel()
    {

    }

    /*
     * 设置支付项
     * */
}